import { api } from '@/api/api';

export interface OllamaModel {
  name: string;
  model: string;
  modified_at: string;
  size: number;
  digest: string;
}

export interface ModelResponse {
  success: boolean;
  message?: string;
  model?: string;
  type?: string;
  previous_model?: string;
}

class OllamaService {
  async getModels(): Promise<OllamaModel[]> {
    console.log('开始获取模型列表');
    try {
      const health = await this.checkHealth();
      console.log('健康检查结果:', health);
      if (!health?.success || (health.status && health.status !== 'healthy')) {
        console.log('健康检查失败，但仍尝试获取模型列表');
        // 不再抛出错误，而是继续尝试获取模型列表
      }

      console.log('开始获取模型列表');
      const { data } = await api.get<{ models?: Array<OllamaModel | string> }>('/v1/llm/ollama/models');
      console.log('获取到的模型数据:', data);
      const rawModels = Array.isArray(data?.models) ? data.models : [];
      console.log('处理后的模型列表:', rawModels);
      return rawModels.map((model, index) => {
        if (typeof model === 'string') {
          return {
            name: model,
            model,
            modified_at: '',
            size: 0,
            digest: `auto-${index}`,
          };
        }
        return model;
      });
    } catch (error) {
      console.error('获取模型列表失败:', error);
      // 如果健康检查失败但模型列表获取成功，返回空数组而不是抛出错误
      return [];
    }
  }

  async switchModel(model: string, sessionId?: string): Promise<ModelResponse> {
    const params: Record<string, any> = { model };
    if (sessionId) {
      params.session_id = sessionId;
    }

    const { data } = await api.post<ModelResponse>('/v1/llm/ollama/use-model', {}, { params });
    return data;
  }

  async getCurrentModel(sessionId?: string): Promise<{ model: string; type: string }> {
    const params: Record<string, any> = {};
    if (sessionId) {
      params.session_id = sessionId;
    }

    const { data } = await api.get<{ model: string; type: string }>('/v1/llm/ollama/current-model', {
      params,
    });
    return data;
  }

  async checkHealth(): Promise<{
    success: boolean;
    status: string;
    version?: string;
    base_url?: string;
  }> {
    try {
      console.log('开始健康检查');
      const { data } = await api.get<{
        success: boolean;
        status: string;
        version?: string;
        base_url?: string;
      }>('/v1/llm/ollama/health');
      console.log('健康检查响应:', data);
      return data;
    } catch (error) {
      console.error('Failed to check Ollama health:', error);
      return {
        success: false,
        status: 'unreachable',
      };
    }
  }

  async refreshModels(): Promise<{ success: boolean; message?: string }> {
    const { data } = await api.post<{ success: boolean; message?: string }>(
      '/v1/llm/ollama/refresh-models'
    );
    return data ?? { success: true };
  }
}

export default new OllamaService();
